import axios from 'axios'

export default {
  data () {
    return {
      // 列表数据
      userList: [],
      // 当前页数
      pageNum: 1,
      // 每页个数
      pageSize: 2,
      total: 0,
      searchText: '',
      temp: '',
      dialogFormVisible: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },

      dialogEditFormVisible: false,
      userEditForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 分配角色
      dialogRolesFormVisible: false,
      Rolesform: {
        rid: -1,
        username: ''
      },
      rolesList: [],

      // 验证规则
      rules: {
        username: [
          // 如果不填 触发这个
          { required: true, message: '输入用户名', trigger: 'blur' },
          // 如果填写错误 触发这个
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '输入密码', trigger: 'blur' },
          // 如果填写错误 触发这个
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          // 如果填写错误 触发这个
          {
            pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
            message: '格式不正确',
            trigger: 'blur'
          }
        ],
        mobile: [
          // 如果填写错误 触发这个
          {
            pattern: /^1(3|4|5|7|8)\d{9}$/,
            message: '格式不正确',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.MLLoadUserList(this.pageNum)
    this.getRolesList()
  },
  methods: {
    async MLLoadUserList (pagenum = 1, query = '') {
      const res = await this.$axios.get(
        'http://localhost:8888/api/private/v1/users',
        {
          params: {
            query,
            pagenum,
            pagesize: this.pageSize
          },
          headers: {
            Authorization: localStorage.getItem('token')
          }
        }
      )

      // console.log(res)
      // 保存数据 用 : 展示数据
      this.userList = res.data.data.users
      // pageNum  用 : 分页点击用
      this.pageNum = res.data.data.pagenum
      // 总条数 用 : 分页
      this.total = res.data.data.total
    },
    changCurrent (currentPage) {
      console.log('改变了', currentPage)
      // 获取最新页 发送请求
      this.MLLoadUserList(currentPage)
    },
    startSearch () {
      // 1. 拿到 text 值
      if (this.searchText.trim().length === 0) {
        return
      }
      console.log('查询')

      // 2. 发送请求
      this.MLLoadUserList(1, this.searchText)
    },
    async delUser (id) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 1. 发送请求删除用户
        await this.$axios.delete(`/users/${id}`)

        // 2. 删除完了 ,重新刷新页面
        this.MLLoadUserList(1, this.searchText)

        // 提示成功
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      } catch (error) {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
    },
    // 修改yoghurt状态
    async changeUserState (row) {
      const { id, mg_state: mgState } = row

      console.log(this.$axios === axios)

      const res = await this.$axios.put(`/users/${id}/state/${mgState}`, null)

      // 提示成功
      this.$message({
        type: 'success',
        message: res.data.meta.msg
      })
    },

    // 添加用户弹窗
    alertAddUserDialog () {
      this.dialogFormVisible = true
    },
    closeDialog () {
      // console.log('关闭对话框')
      this.$refs.addUserForm.resetFields()
    },
    async addUser () {
      try {
        // 1. 表单校验 refs
        await this.$refs.addUserForm.validate()
        console.log('验证成功')
        // 2. 添加用户
        const res = await this.$axios.post('/users', this.addUserForm)
        console.log(res)

        // 3. 关闭对话框
        this.dialogFormVisible = false

        // 更新一下
        this.MLLoadUserList()

        // 4. 弹框
        this.$message({
          type: 'success',
          message: '添加用户成功'
        })
      } catch (error) {
        console.log('验证失败')
      }
    },

    // 展示编辑对话框
    showUserEditDialog (curUser) {
      console.log('准备展示编辑对话框', curUser)
      this.userEditForm.username = curUser.username
      this.userEditForm.email = curUser.email
      this.userEditForm.mobile = curUser.mobile
      this.userEditForm.id = curUser.id
      this.dialogEditFormVisible = true
    },
    // 点击确定 修改用户
    async editUser () {
      // console.log(this.userEditForm.id)

      const { id, email, mobile } = this.userEditForm

      const res = await this.$axios.put(`/users/${id}`, {
        email,
        mobile
      })

      if (res.data.meta.status === 200) {
        // 1. 关闭对话框
        this.dialogEditFormVisible = false
        // 2. 更新列表
        this.MLLoadUserList()
        // 3. 弹窗
        this.$message({
          type: 'success',
          message: res.data.meta.msg
        })
      }
    },

    // 展示分配角色对话框
    async showRolesDialog (curRol) {
      console.log(curRol.id)

      // 根据id 获取对应的信息
      const res = await this.$axios.get(`/users/${curRol.id}`)
      console.log(res)
      this.Rolesform.username = curRol.username
      this.Rolesform.rid = res.data.data.rid === -1 ? '' : res.data.data.rid
      this.Rolesform.id = curRol.id

      this.dialogRolesFormVisible = true
    },
    async getRolesList () {
      const res = await this.$axios.get('/roles')

      this.rolesList = res.data.data
    },
    // 选择角色
    async selectedRoles () {
      console.log(this.Rolesform)

      const { id, rid } = this.Rolesform

      const res = await this.$axios.put(`/users/${id}/role`, {
        rid
      })

      // 1. 关闭对话框
      this.dialogRolesFormVisible = false
      // 2. 刷新数据
      this.MLLoadUserList()
      // 3. 提示成功
      this.$message({
        type: 'success',
        message: res.data.meta.msg
      })
    }
  }
}
